package com.tuling.jvm;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by chenhs on 2018/8/3.
 *
 * 【Java堆内存溢出异常测试】
 *
 * VM Args：-Xms20m -Xmx20m -XX:+HeapDumpOnOutOfMemoryError
 *
 */
public class HeapOOM {

    static class OOMObject {
        String name = "Ters";
        int age = 18;

        public void say() {
            System.out.println(name + " " + age);
        }
    }

    public static void main(String[] args) {
        List<OOMObject> list = new ArrayList<OOMObject>();
        int i = 0;
        while (true) {
            System.out.println(i++);
            list.add(new OOMObject());
        }

        /**
         Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
         at java.util.Arrays.copyOf(Arrays.java:3210)
         at java.util.Arrays.copyOf(Arrays.java:3181)
         at java.util.ArrayList.grow(ArrayList.java:261)
         at java.util.ArrayList.ensureExplicitCapacity(ArrayList.java:235)
         at java.util.ArrayList.ensureCapacityInternal(ArrayList.java:227)
         at java.util.ArrayList.add(ArrayList.java:458)
         at com.tuling.jvm.HeapOOM.main(HeapOOM.java:30)
         */
    }

}
